package cn.rlfit.gulimall.product.exception;

import cn.rlfit.common.exception.BizCodeEnume;
import cn.rlfit.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ruolifeng [1877751412@qq.com]
 * @date 2023/2/22 22:00
 * 集中处理所有数据异常
 */
@Slf4j
@RestControllerAdvice(basePackages = "cn.rlfit.gulimall.product.controller")
//@ControllerAdvice(basePackages = "cn.rlfit.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e) {
        Map<String, String> map = new HashMap<>(10);
        log.error("数据校验出现问题：{}，异常类型：{}", e.getMessage(), e.getClass());
        e.getBindingResult().getFieldErrors().forEach(item -> {
            String field = item.getField();
            String defaultMessage = item.getDefaultMessage();
            map.put(defaultMessage, field);
        });
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(), BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data", map);
    }

    @ExceptionHandler(Throwable.class)
    public R handlerException(Throwable e) {
        log.error("系统未知异常：{}，异常类型：{}", e.getMessage(), e.getClass());
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}
